﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;



using  Medart.Models;
 
using DHTMLX.Scheduler;
using DHTMLX.Scheduler.Data;
using DHTMLX.Common;
using DHTMLX.Scheduler.Controls;
 
namespace  Medart.Controllers{

    public class BasicSchedulerController : Controller
    {
        HMS909Context db = new HMS909Context();
        DHXScheduler scheduler = null;
        public ActionResult Index(string  patID, string name, string aname, string doctors, string sp)
        {

            this.Init(patID, name, aname, doctors, sp);
            var context = new CalendarDataContext();
            scheduler = new DHXScheduler(this);
            
            if(doctors != null)
            {
                var dd  = context.Events.Where(xr => xr.docID == int.Parse(doctors)).ToList();
                foreach(var r in dd)
                {
                    scheduler.TimeSpans.Add(new DHXMarkTime()
                    {
                        StartDate = r.start_date,
                        EndDate =  r.end_date,
                        CssClass = "green_section",

                        
                    });
 
                }
            }
    
     //       scheduler.TimeSpans.Add(new DHXMarkTime()
       //     {
        //        Day = DayOfWeek.Saturday, //marks each Saturday with the 'green_section' style
         //       CssClass = "green_section"
          //  });
            scheduler.Skin = DHXScheduler.Skins.Terrace;
            scheduler.Config.multi_day = true;//render multiday events
            scheduler.LoadData = true;
            scheduler.EnableDataprocessor = true;
            IEnumerable<SelectListItem> items = context.DoctorsMAs.Select(c => new SelectListItem
            {
                Value = c.key.ToString(),
                Text = c.English + " - " + c.Arabic
            });
            if(doctors!= null)
            {
                int index = int.Parse(doctors);
                foreach (var item in items.ToList())
                {
                    if(item.Value == doctors)
                    {
                        item.Selected = true;
                        break;
                    }

                }
            }

            ViewBag.doctors = items;
            items = context.SpecialtyMAs.Select(c => new SelectListItem
            {
                Value = c.key.ToString(),
                Text = c.arabic + " - " + c.english
            });
            if (sp != null)
            {
                foreach (var item in items.ToList())
                {
                    if (item.Value == sp)
                    {
                        item.Selected = true;
                        break;
                    }

                }
            }
            ViewBag.sp = items;


            scheduler.Extensions.Add(SchedulerExtensions.Extension.Collision);
           // scheduler.Extensions.Add(SchedulerExtensions.Extension.Limit);

            scheduler.Config.first_hour = 9;
            scheduler.Config.last_hour = 22;
            scheduler.XY.scroll_width = 100;
            scheduler.Config.time_step = 15; // minimum event length
            scheduler.Config.multi_day = false;
            //scheduler.Config.limit_time_select = true;

            scheduler.Config.cascade_event_display = true;


            scheduler.AfterInit = new List<string>() { "attachRules();" };// The required client-side handlers have to be added after Scheduler initialization but before events load.


            //scheduler.LoadData = true;


           // scheduler.Views.Clear();

            

            var rooms = context.RoomsMAs.ToList();;
            var units = new UnitsView("RoomsMAs", "roomID");
            if(sp != null)
            {
                rooms = context.RoomsMAs.Where(xx => xx.DEPARTMENT == int.Parse(sp)).ToList();
            }
         

            units.Label = "Rooms";
            units.AddOptions(rooms);
            scheduler.Views.Add(units);
          
            scheduler.Views.Add(new WeekAgendaView());

            var select = new LightboxSelect("roomID", "RoomsMA");
            select.AddOptions(context.RoomsMAs);
            scheduler.Lightbox.AddDefaults();
            scheduler.Lightbox.Items.Insert(1, select);
            var box = scheduler.Lightbox.SetExternalLightbox("BasicScheduler/LightboxControl", 800, 800);
            box.ClassName = "custom_lightbox";
            scheduler.InitialView = units.Name;
            var clrs =  context.COLORs.ToList();
            var cal = new MiniCalendar("container_id");// initialization
            cal.Navigation = true;// configuration
            scheduler.Calendars.Add(cal);// adding to the page
            scheduler.Config.separate_short_events = true;
            return View(new CalendarModel()
            {
                Rooms = rooms,
                cls = clrs,
                Scheduler = scheduler
            }
            );
  

        }

        private void Init(string patID, string name, string aname, string doctors, string sp)
        {
            if (patID != null)
            {
                Session["patID"] = patID;
                ViewBag.patID = patID;


            }
            else
            {
                Session["patID"] = null;
                ViewBag.patID = null;
            }
            if (doctors != null)
            {
                Session["doctors"] = doctors;
                ViewBag.doctors = doctors;
            }
            else
            {
                Session["doctors"] = null;
                ViewBag.doctors = null;
            }
            if (sp != null)
            {
                Session["sp"] = sp;
                ViewBag.sp = sp;
            }
            else
            {
                Session["sp"] = null;
                ViewBag.sp = null;
            }
            if (name != null)
            {
                Session["name"] = name;
                ViewBag.name = name;
            }
            else
            {
                Session[name] = null;
                ViewBag.name = null;
            }
            if (aname != null)
            {
                Session["aname"] = aname;
                ViewBag.aname = aname;
            }
            else
            {
                Session[aname] = null;
                ViewBag.aname = null;
            }
        }
        public ActionResult LightboxControl(Event ev)
        {

            var context = new CalendarDataContext();

            int[] hours = new int[12];
            int index = 0;
          
            List<int> hoursList = new List<int>();
            index = 0;
            for (int i = 9; i < 12; i++)
            {
                hoursList.Add( i);
            }
            for (int i = 12; i < 25; i++)
            {
               hoursList.Add(i);
            }

          
            List<int> minList = new List<int>();
            index = 0;
            for (int i = 1; i < 61; i++)
            {
                minList.Add(i);
            }



            //--------------



            //-------
            //var context = new DHXSchedulerModelsDataContext();
            var current = context.Events.SingleOrDefault(e => e.id == ev.id);
            if (current == null)
            {
                
                IEnumerable<SelectListItem> items = context.COLORs.Select(c => new SelectListItem
                {
                    Value = c.ID.ToString(),
                    Text = c.LABEL
                });
                ViewBag.color = items;
                current = ev;
                String docID = (String)Session["doctors"];
                String patID = (String)Session["patID"];
                
                if(docID != null && patID != null)
                {
                    current.docID = int.Parse((String)Session["doctors"]);
                    current.patID = (String)Session["patID"];

                    DoctorsMA doctor = context.DoctorsMAs.FirstOrDefault(c => c.key == current.docID);
                    ViewBag.doctor = doctor;
                    
                    CustomerList customer = db.Customers.FirstOrDefault(c => c.ID.Equals(current.patID));
                    ViewBag.customer = customer;
                    String n =  " \n ";
                    current.text = doctor.English + n;
                    current.text = current.text + "Pat. " + customer.englishName + " - " + customer.arabicName + n + customer.mobile
                        + n + " Record No. " + customer.recordNumber;

                    
                }else
                {
                   
                }

                
            }else
            {
                IEnumerable<SelectListItem> items = context.COLORs.Select(c => new SelectListItem
                {
                    Value = c.ID.ToString(),
                    Text = c.LABEL
                });
                foreach(var i in items)

                {
                    if(i.Value.Equals(current.color))
                    {
                        i.Selected = true;
                        break;
                    }
                }

                ViewBag.color = items;
                DoctorsMA doctor = context.DoctorsMAs.FirstOrDefault(c => c.key == current.docID);
                ViewBag.doctor = doctor;

                CustomerList customer = db.Customers.FirstOrDefault(c => c.ID.Equals(current.patID));
                ViewBag.customer = customer;
                String n = " \n ";

            }

            int roomID = current.roomID;

            var room = context.RoomsMAs.SingleOrDefault(s => s.key == roomID);
         
            ViewBag.room = room;
            SelectList mins = new SelectList(minList, current.start_date.Minute);
            ViewBag.fromMinList = mins;
            SelectList l = new SelectList(hoursList, current.start_date.Hour);
            ViewBag.fromHourList = l;
            SelectList toHousList = new SelectList(hoursList, current.end_date.Hour);
            ViewBag.toHourList = toHousList;
            SelectList toMins = new SelectList(minList, current.end_date.Minute);
            ViewBag.toMinList = toMins;
                
            return View(current);
        }
      

        public ActionResult Data()
        {//events for loading to scheduler
            return new SchedulerAjaxData(new CalendarDataContext().Events);
        }
          public ActionResult Save(int? id, FormCollection actionValues)
        {
            var action = new DataAction(actionValues);
            var status2 = actionValues["status1"];

            var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), actionValues);
            if (status2 != null)
            {
                int con = int.Parse(status2);
                changedEvent.confirmed = con;

            }
            if (action.Type != DataActionTypes.Error)
            {
                //process resize, d'n'd operations...
                return NativeSave(changedEvent, actionValues);
            }
            else
            {
                //custom form operation
                return CustomSave(changedEvent, actionValues);
            }

        }
 
          public JsonResult AutocompleteSuggestions(string term)
          {
              String str = term;
              string query = "select company as englishName , aname as arabicName, ID, mobile, phone, caseNb as recordNumber, id_no as natID from [hms909].[dbo].[Cust] where company like '%" + str + "%' or aname like '%" + str + "%' or mobile like '%" + str + "%' or  phone like '%" + str + "%' or caseNb like '%" + str + "%' or  id_no like '%" + str + "%'";

              var list = db.Database.SqlQuery<CustomerList>(query);
              return Json(list.AsQueryable(), JsonRequestBehavior.AllowGet);
          }
        public ActionResult CustomSave(Event changedEvent, FormCollection actionValues)
        {
            int shit = int.Parse((String)Session["doctors"]);
            if (changedEvent == null)
            {
                
                changedEvent.docID = int.Parse((String)Session["doctors"]);
                changedEvent.patID = (String)Session["patID"];

            }
              
            var action = new DataAction(DataActionTypes.Update, changedEvent.id, changedEvent.id);
            if (actionValues["actionButton"] != null)
            {
                CalendarDataContext data = new CalendarDataContext();
                try
                {
                    if (actionValues["actionButton"] == "Save - حفظ")
                    {

                        if (data.Events.SingleOrDefault(ev => ev.id == action.SourceId) != null)
                        {
                            var eventToUpdate = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                            DHXEventsHelper.Update(eventToUpdate, changedEvent, new List<string>() { "id" });                           
                        }
                        else
                        {
                            action.Type = DataActionTypes.Insert;
                            data.Events.InsertOnSubmit(changedEvent);
                          
                
                        }
                    }
                    else if (actionValues["actionButton"] == "Cancel  - الغاء")
                    {
                        action.Type = DataActionTypes.Delete;
                        changedEvent = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                        data.Events.DeleteOnSubmit(changedEvent);
                    }                       
                    data.SubmitChanges();
                }

                catch(Exception e)
                {

                    action.Type = DataActionTypes.Error;
                }
            }
            else
            {
                action.Type = DataActionTypes.Error;
            }


            return (new SchedulerFormResponseScript(action, changedEvent));
           
        }

        public ContentResult NativeSave(Event changedEvent, FormCollection actionValues)
        {

            var action = new DataAction(actionValues);

            CalendarDataContext data = new CalendarDataContext();
            try
            {
                switch (action.Type)
                {
                    case DataActionTypes.Insert:
                        data.Events.InsertOnSubmit(changedEvent);
                        break;
                    case DataActionTypes.Delete:
                        changedEvent = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                        data.Events.DeleteOnSubmit(changedEvent);
                        break;
                    default:// "update"                          
                        var eventToUpdate = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                        DHXEventsHelper.Update(eventToUpdate, changedEvent, new List<string>() { "id" });  
                        break;
                }
                data.SubmitChanges();
                action.TargetId = changedEvent.id;
            }
            catch 
            {
                action.Type = DataActionTypes.Error;
            }

            return (new AjaxSaveResponse(action));
        }
        


    }
}
